package com.jihox.abookpro.dao;

import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.jihox.abookpro.domain.Material;
import com.jihox.abookpro.util.DBHelper;

public class MaterialDAO {

	private Context context;
	private DBHelper dbhelper;
	private SQLiteDatabase sqlitedatabase;

	public MaterialDAO(Context context) {
		super();
		this.context = context;
	}
	
	public void opendb() {
		dbhelper = new DBHelper(context);
		sqlitedatabase = dbhelper.getWritableDatabase();
	}

	public void closedb() {
		if (sqlitedatabase != null && sqlitedatabase.isOpen()) {
			sqlitedatabase.close();
		}
	}
	
	//向数据库中添加一条Material
	public void addMaterial(Material material) {
		ContentValues cv = new ContentValues();
		cv.put("Name", material.getName());
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		material.getPicture().compress(Bitmap.CompressFormat.JPEG, 100, os);
		cv.put("Picture", os.toByteArray());
		opendb();
		sqlitedatabase.insert("material", null, cv);
		closedb();
	}
	
	//从数据库中删除一条Material
	public void deleteMaterial(String name) {
		opendb();
		try {
			sqlitedatabase.delete("material", "Name = ?", new String[] {name});
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closedb();
		}
	}
	
	//根据name查询特定的Material
	public Material getMaterial(String name) {
		Material material = new Material();
		opendb();
		Cursor c = sqlitedatabase.rawQuery("SELECT * FROM material where Name = '" + name +"'", null);
		while(c.moveToNext()){
			material.setName(c.getString(c.getColumnIndex("Name")));
			byte[] in=c.getBlob(c.getColumnIndex("Picture"));  
			material.setPicture(BitmapFactory.decodeByteArray(in,0,in.length));  
		}
		c.close();
		closedb();
		return material;
	}

}


